import axios from 'axios';
import Cookies from 'js-cookie';

function storeToken(token, expires) {
    Cookies.set('token', token, {
        path: '/',
        secure: true, // 仅在 HTTPS 下使用
        sameSite: 'Strict', // 防止 CSRF
        expires: expires // 设置过期时间（7 天）
    });
}

function getToken() {
    return Cookies.get('token');
}

function removeToken() {
    Cookies.remove('token', { path: '/' });
}

const apiClient = axios.create({
    baseURL: 'http://localhost:9000/api',
    headers: {
        'Content-Type': 'application/json;charset=UTF-8',
    },
});

// 请求拦截器：动态添加 Token
apiClient.interceptors.request.use(config => {
    const token = getToken();
    if (token) {
        config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
}, error => {
    return Promise.reject(error);
});

// 登录
function login(username, password) {
    return apiClient.post('/auth/login', {
        username: username,
        password: password
    }, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        }
    }).catch(error => {
        console.error(error);
    });
}
// 登出
function logout() {
    return apiClient.get('/auth/logout').catch(error => {
        console.error(error);
    });
}
// 用户接口
function findBookU() {
    return apiClient.get('/user/find/book');
}
function findBookByTitle(title) {
    return apiClient.post(`/user/find/book?title=${title}`);
}
function findRecord() {
    return apiClient.get('/user/find/record');
}
function borrowBook(bookId) {
    return apiClient.post(`/user/borrow/${bookId}`);
}
function returnBook(recordId) {
    return apiClient.post(`/user/return/${recordId}`);
}
// 管理员接口
function findUser() {
    return apiClient.get('/admin/find/user');
}
function addUser(user) {
    return apiClient.post('admin/add/user', user);
}
function editUser(user) {
    return apiClient.post('admin/edit/user', user);
}
function deleteUser(userId) {
    return apiClient.delete(`admin/delete/user/${userId}`);
}
function findBookA() {
    return apiClient.get('/admin/find/book');
}
function addBook(book) {
    return apiClient.post('admin/add/book', book);
}
function editBook(book) {
    return apiClient.post('admin/edit/book', book);
}
function deleteBook(bookId) {
    return apiClient.delete(`admin/delete/book/${bookId}`);
}

export default {
    login, logout, findBookU, findBookByTitle, findRecord, borrowBook, returnBook,
    findUser, addUser, editUser, deleteUser, findBookA, addBook, editBook, deleteBook,
    storeToken, getToken, removeToken,
};
